package req

import (
	"fmt"
	"gitee.com/whilew/cream/pkg/basic_component/log"
	"github.com/google/uuid"
	"github.com/imroc/req/v3"
	"time"
)

type iReqLoger func(resp *req.Response, loger *log.Loger)

func RGet(r *req.Request, url string, logh ...iReqLoger) (*req.Response, error) {
	var (
		start  = time.Now()
		status = 0
		req_id = uuid.New().String()
		loger  = log.WithModule("request").WithKV("req_id", req_id)
	)
	defer func() {
		// GET http://baidu.com 200ms
		loger.Info(fmt.Sprintf("GET %s %d %s", url, status, time.Now().Sub(start)), "type", "info")
	}()
	resp, err := r.Get(url)
	for _, t := range logh {
		t(resp, loger)
	}
	if err != nil {
		status = 500
		loger.WithKV("success", false)
		loger.Error(err.Error(), "type", "error")
		return nil, err
	}
	status = resp.StatusCode
	return resp, err
}
func RPost(r *req.Request, url string, logh ...iReqLoger) (*req.Response, error) {
	var (
		start  = time.Now()
		status = 0
		req_id = uuid.New().String()
		loger  = log.WithModule("request").WithKV("req_id", req_id)
	)
	defer func() {
		// POST http://baidu.com 200ms
		loger.Info(fmt.Sprintf("POST %s %d %s", url, status, time.Now().Sub(start)), "type", "info")
	}()
	resp, err := r.Post(url)
	for _, t := range logh {
		t(resp, loger)
	}
	if err != nil {
		status = 500
		loger.WithKV("success", false)
		loger.Error(err.Error(), "type", "error")
		return nil, err
	}
	if !resp.IsSuccess() {
		status = resp.StatusCode
		loger.WithKV("success", false)
	}
	return resp, err
}

func RPut(r *req.Request, url string, logh ...iReqLoger) (*req.Response, error) {
	var (
		start  = time.Now()
		status = 0
		req_id = uuid.New().String()
		loger  = log.WithModule("request").WithKV("req_id", req_id)
	)
	defer func() {
		// POST http://baidu.com 200ms
		loger.Info(fmt.Sprintf("PUT %s %d %s", url, status, time.Now().Sub(start)), "type", "info")
	}()
	resp, err := r.Put(url)
	for _, t := range logh {
		t(resp, loger)
	}
	if err != nil {
		status = 500
		loger.WithKV("success", false)
		loger.Error(err.Error(), "type", "error")
		return nil, err
	}
	if !resp.IsSuccess() {
		status = resp.StatusCode
		loger.WithKV("success", false)
	}
	return resp, err
}

// todo 无效
func WithRespDump(resp *req.Response, loger *log.Loger) {
	if resp.Dump() != "" {
		loger.Info(resp.Dump(), "type", "dump")
	}
}
func WithRespStr(resp *req.Response, loger *log.Loger) {
	if resp_str, err := resp.ToString(); err != nil {
		loger.Error("to string err: "+err.Error(), "type", "error")
	} else {
		loger.Info(resp_str, "type", "resp")
	}
}
